package com.example.esp32;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class additme extends AppCompatActivity {
    private ImageButton daa, TUC;
    private SwipeRefreshLayout additmesw;
    private List<getValue> ddList = new ArrayList<getValue>();
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_additme);
        additmesw = findViewById(R.id.additmesw);
        boolean lis=list();
        additmesw.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(lis){
//                    list();
                    additmesw.setRefreshing(false);


                }            }
        });
        ProgressDialog progressDialog1 = new ProgressDialog(this);
        progressDialog1.setMessage("正在加载中");
        progressDialog1.show();
        TUC = findViewById(R.id.TUC);
        TUC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {

                progressDialog1.dismiss();

            }
        }, 2000);
        daa = (ImageButton) findViewById(R.id.add);
        daa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ddList.clear();
                tck();
            }
        });
        listView = findViewById(R.id.grview);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//监听list里面的itme的点击事件
                String a = ((TextView) view.findViewById(R.id.id)).getText().toString();
                String as = ((TextView) view.findViewById(R.id.xhqd)).getText().toString();

                Intent intent = new Intent();
                intent.putExtra("myText", a);
                intent.putExtra("id", as);

                intent.setClass(additme.this, itmeaddr.class);
                startActivity(intent);
                Toast.makeText(additme.this, "第" + position + "个item", Toast.LENGTH_SHORT).show();


            }
        });
    }

    private void addpost(String clientid, String topic, String view) {
        new Thread() {
            @Override
            public void run() {
                super.run();

                request request = new request();
                JSONObject jsonObject = new JSONObject();

                try {
                    jsonObject.put("clientid", clientid);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                try {
                    jsonObject.put("topic", topic);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                try {
                    jsonObject.put("name", view);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                String a;
                try {
                    a = jsonObject.toString(1);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                String data = a;
                String resq = request.post("http://ipzhangt:8999/additme", data);
                Log.d(TAG, resq);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        list();


                    }
                });
            }
        }.start();


    }

    public void tck() {
//    edit_one = (EditText) findViewById(R.id.edit_one);
        LayoutInflater factory = LayoutInflater.from(additme.this);
        final View DialogView = factory.inflate(R.layout.input, null);
//    AlertDialog.Builder builder=new AlertDialog.Builder(pew.this);

        AlertDialog dlg = new AlertDialog.Builder(additme.this)
                .setTitle("添加新设备")
                .setView(DialogView)//设置自定义对话框的样式
                .setPositiveButton("确定", //设置"确定"按钮
                        new DialogInterface.OnClickListener() //设置事件监听
                        {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //输入后点击“确定”，开始获取我们要的内容 DialogView就是AlertDialog弹出的Activity
                                EditText vi = (EditText) DialogView.findViewById(R.id.view);
                                String cc = vi.getText().toString();
                                EditText cid = (EditText) DialogView.findViewById(R.id.cid);
                                EditText tcp = (EditText) DialogView.findViewById(R.id.tcp);
//                                Spinner vi = (Spinner) DialogView.findViewById(R.id.view);
//                                String cc=vi.getSelectedItem().toString();
                                String pawer = cid.getText().toString();
                                String as = tcp.getText().toString();

                                if (pawer.equals("") || as.equals("") || cc.equals("")) {
                                    list();
                                    Toast.makeText(additme.this, "不能有空值", Toast.LENGTH_LONG).show();
                                } else {
                                    addpost(pawer, as, cc);
                                    Log.d(TAG, pawer);
                                }
                            }
                        })
                .create();//创建弹出框
        dlg.show();//显示
    }

    public boolean list() {
        final int[] itmes = new int[1];
        /*get请求获取数据并更新到lis里*/
        new Thread() {
            @Override
            public void run() {
                super.run();
                request request = new request();
//                    String data="wifi"+"="+SSID+"&"+"password"+"="+PAWWER;

                String resq = request.get("http://ipzhangt:8999/additme");
                Log.d(TAG, resq);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

//                        String[] arrayData=resq.split("\\>");
                        try {
                            JSONObject jsonObjectc = new JSONObject(resq);
                            int itme = jsonObjectc.optInt("itme");
                            if (itme == 0) {
                                Toast.makeText(additme.this, "没有设备", Toast.LENGTH_LONG).show();

                            }
                            itmes[0] = itme;


                            for (int i = 0; i < itme; i++) {
                                String aadd = jsonObjectc.optString("data" + i);

                                JSONObject jsonObject = new JSONObject(aadd);
                                getValue dd = new getValue();
                                String zt = jsonObject.optString("name");
                                String idd = jsonObject.optString("id");
                                String aa = jsonObject.optString("clientid");
                                String zz = jsonObject.optString("topic");
                                dd.setsbmc(idd);

                                dd.setas(zt);
                                dd.setip(aa);
                                dd.setdyzt(zz);
                                ddList.add(dd);
                                Log.d(TAG, resq);
                            }
                            listView = findViewById(R.id.grview);
                            GAdapter adapter = new GAdapter(additme.this, ddList);
                            listView.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
            }
        }.start();
        if(itmes[0]<=0){
            return true;
        }else {
            return false;
        }
    }
}